package com.common.ui.controls;

import java.awt.Frame;

import javax.swing.SwingUtilities;

abstract public class ModalProcess implements Runnable
{
	private String processName;
	private Thread thread;
	private Object argument;
	private boolean isCancelled;
	private ModalProgressDialog dialog;
	private Frame owner;
	
	public ModalProcess(String processName,Frame owner)
	{
		this(processName,owner,null);
	}
	
	public ModalProcess(String processName,Frame owner,ModalProgressDialog  dialog)
	{
		this.processName = processName;
		isCancelled = false;
		if(dialog==null)
		{
			dialog = new DefaultModalProgressDialog(this,owner);
		}
		this.owner = owner;
		this.dialog = dialog;		
	}

	public String getProcessName() 
	{
		return processName;
	}

	public void setProcessName(String processName) 
	{
		this.processName = processName;
	}
	
	public void start(Object argument)
	{
		this.argument = argument;
		thread = new Thread(this);
		thread.start();
		dialog.showProgress();
	}
	
	public void updateStatus(final Object detail,final boolean newLine)
	{
		SwingUtilities.invokeLater(new Runnable() 
		{
			public void run() 
			{
				dialog.updateStatus(detail, newLine);
			}
		});
	}

	public void updateInfo(final Object info)
	{
		SwingUtilities.invokeLater(new Runnable() 
		{
			public void run() 
			{
				dialog.updateInfo(info);
			}
		});
	}
	
	public abstract void doWork(Object argument) throws Exception;
	
	public void run()
	{
		Exception ex = null;
		try
		{
			doWork(argument);
		}
		catch(Exception e)
		{
			ex = e;
		}
		dialog.dispose();
		done(ex);
	}
	
	public void cancel()
	{
		if(canCancel())
		{
			performCancel();
		}
	}
	
	private void performCancel()
	{
		isCancelled = true;
	}
	
	public abstract boolean canCancel();
	public abstract void done(Exception e);

	public boolean isCancelled() 
	{
		return isCancelled;
	}

	public Frame getOwner() {
		return owner;
	}
}
